package com.saxion.conc;

import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;


public class OnePointTwo{
	
	int	array	= 25000;
	ArrayList<Integer>	first, second = new ArrayList<Integer>();
	long				startTime;
	int					numberOfThreads;
	
	
	public OnePointTwo( int numberOfThreads ) {
		first = new ArrayList<Integer>();
		second = new ArrayList<Integer>();
		this.numberOfThreads = numberOfThreads;
		for( int i = 0; i < 5; i++ ){
			start();
		}
	}
	
	
	private void start() {
		ExecutorService executor = Executors.newFixedThreadPool( numberOfThreads );
		ArrayList<Integer> numberArray = fillArray();
		try{
			if( numberOfThreads == 2 )
				splitArray( numberArray );
			
			startTime = System.nanoTime();
			if( numberOfThreads == 2 )
				addToPool( executor );
			else
				addToPool( executor, numberArray );
		} finally{
			executor.shutdown();
		}
		try{
			executor.awaitTermination( 15, TimeUnit.SECONDS );
		} catch( InterruptedException e ){
			Thread.currentThread().interrupt();
		}
		System.out.print( "1.2: Completed in " + ( System.nanoTime() - startTime ) / 1000000 + " ms\n" );
	}
	
	
	private void addToPool( ExecutorService executor ) {
		Runnable oPOne = new OnePointOne( first );
		executor.execute( oPOne );
		Runnable oPTwo = new OnePointOne( second );
		executor.execute( oPTwo );
	}
	
	
	private void addToPool( ExecutorService executor, ArrayList<Integer> numbersArray ) {
		Runnable oPO = new OnePointOne( numbersArray );
		executor.execute( oPO );
	}
	
	
	private void splitArray( ArrayList<Integer> array ) {
		for( int i = array.size() / 2; i > 0; i-- ){
			first.add( array.remove( i ) );
		}
		second = array;
	}
	
	
	private ArrayList<Integer> fillArray() {
		ArrayList<Integer> numberArray = new ArrayList<Integer>();
		Random generator = new Random();
		
		for( int i = 0; i < array; i++ ){
			numberArray.add( generator.nextInt() );
		}
		return numberArray;
	}
	
}
